<template>
  <el-container>
    <div style="width: 30%; border-right: 1px solid #ccc; padding: 10px">
      <el-form @submit.prevent class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="组织名称"
            prefix-icon="Search"
            @keyup.enter="exeOrgFilter"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-tree
        ref="orgTree"
        :data="organizationTree"
        :props="defaultProps"
        default-expand-all
        node-key="id"
        highlight-current
        @node-click="handleNodeClick"
        :filter-node-method="filterNode"
      ></el-tree>
    </div>
    <div style="flex: 1; padding: 10px">
      <el-text class="cus-title">{{
        selectedOrganization.name ? selectedOrganization.name : ""
      }}</el-text>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" @click="onAddOrganization" icon="CirclePlus"
        >新增组织</el-button
      >
      <el-divider direction="horizontal" style="width: 95%"></el-divider>
      <el-table :data="selectedOrganizationChildren" style="width: 100%">
        <el-table-column prop="id" label="ID" width="100"></el-table-column>
        <el-table-column prop="code" label="编码"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            {{ orgTypes.find((c) => c.value === scope.row.type).label }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="onEdit(scope.row)"
              >编辑</el-button
            >
            <el-button link type="primary" @click="onDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-container>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '修改组织' : '新增组织'"
    width="30%"
    header-class="dialog-custom-header"
  >
  <el-divider direction="horizontal" style="width: 95%"></el-divider>
    <el-form :model="newOrganizationForm" label-width="70px">
      <el-form-item label="编码">
        <el-input
          v-model="newOrganizationForm.code"
          :disabled="isEdit"
        ></el-input>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="newOrganizationForm.name"></el-input>
      </el-form-item>
      <el-form-item label="类型">
        <el-select
          v-model="newOrganizationForm.type"
          placeholder="类型"
          :disabled="isEdit"
        >
          <el-option
            v-for="item in orgTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
          <!-- 其他类型 -->
        </el-select>
      </el-form-item>
      <el-form-item label="父组织" v-if="false">
        <el-input v-model="newOrganizationForm.parent"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from "vue";
import { get, post, put, del } from "@/utils/request";
import { ElMessage } from "element-plus";
const dialogVisible = ref(false);
// const showAddUserDialog = ref(false);
const isEdit = ref(false); // 是否为修改模式
const currentEditId = ref(null); // 当前编辑的组织ID
const orgTree = ref(null);
const newOrganizationForm = reactive({
  id: null,
  code: null,
  name: null,
  type: null,
  parent: null,
});
const organizationTree = ref([
  {
    id: 1,
    code: "ORG001",
    name: "组织1",
    type: 1,
    parent: 0,
    children: [
      {
        id: 2,
        code: "ORG001-1",
        name: "子组织1-1",
        type: 2,
        parent: 1,
      },
    ],
  },
]);
const searchForm = reactive({
  name: null,
});
const selectedOrganization = reactive({
  id: null,
  name: null,
  code: null,
  type: null,
  parent: null,
  children: null,
});
const selectedOrganizationChildren = ref([]);
// const selectedOrganizationUsers = ref([]);
// const searchedUsers = ref([]);
const orgTypes = ref([]);
const defaultProps = {
  children: "children",
  label: "name",
};



const handleNodeClick = (data) => {
  Object.assign(selectedOrganization, data);
  selectedOrganizationChildren.value = selectedOrganization.children || [];
  // selectedOrganizationUsers.value = data.users || [];
};

const onAddOrganization = () => {
  isEdit.value = false;
  if (!selectedOrganization.id) {
    ElMessage.error("请选择组织");
    return;
  }
  Object.keys(newOrganizationForm).forEach((key) => {
    newOrganizationForm[key] = null;
  });
  newOrganizationForm.parent = selectedOrganization.id;
  dialogVisible.value = true;
};

const onEdit = (row) => {
  isEdit.value = true;
  Object.assign(newOrganizationForm, row);
  dialogVisible.value = true;
};

const onDelete = (row) => {
  del("/mdm/orgs/" + row.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        onSearch();
        selectedOrganizationChildren.value =
          selectedOrganizationChildren.value.filter(
            (item) => item.id !== row.id
          );
        ElMessage.success("删除成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onSubmit = async () => {
  let succ = false;
  if (isEdit.value) {
    // 修改组织逻辑
    let payload = {
      name: newOrganizationForm.name,
    };
    await put("/mdm/orgs/" + newOrganizationForm.id, payload)
      .then((res) => {
        if (res.data.code === 0) {
          onSearch();
          selectedOrganizationChildren.value =
            selectedOrganizationChildren.value.map((item) => {
              if (item.id === newOrganizationForm.id) {
                item.name = newOrganizationForm.name;
              }
              return item;
            });
          succ = true;
          ElMessage.success("修改成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  } else {
    // 新增组织逻辑
    let payload = {
      code: newOrganizationForm.code,
      name: newOrganizationForm.name,
      type: newOrganizationForm.type,
      parent: newOrganizationForm.parent,
    };
    await post("/mdm/orgs", payload)
      .then((res) => {
        if (res.data.code === 0) {
          onSearch();
          newOrganizationForm.id = res.data.data.id;
          selectedOrganizationChildren.value.push({
            ...newOrganizationForm,
          });
          succ = true;
          ElMessage.success("新增成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
  if (succ) {
    dialogVisible.value = false;
  }
  
};
const onSearch = () => {
  get("/mdm/orgs")
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        organizationTree.value = res.data.data.data;
        // selectedOrganizationChildren.value = [];
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};
onMounted(async() => {
  // 初始化字典
  await get("/mdm/orgs/types")
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        orgTypes.value = res.data.data.data;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
  await get("/mdm/orgs")
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        organizationTree.value = res.data.data.data;
        selectedOrganizationChildren.value = [];
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
});
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};
const exeOrgFilter = () => {
  console.log(orgTree.value)
  orgTree.value.filter(searchForm.name)
};
</script>

